package org.groupg.practice.Compress;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.GZIPOutputStream;

public class TarGzCreator {
    public static void createTarGz(Path sourceDir, String outputFile) throws IOException {
        try (OutputStream fo = Files.newOutputStream(Paths.get(outputFile));
             GZIPOutputStream gzo = new GZIPOutputStream(fo);
             TarArchiveOutputStream tos = new TarArchiveOutputStream(gzo)) {

            Files.walk(sourceDir)
                .filter(path -> !Files.isDirectory(path))
                .forEach(path -> {
                    String entryName = sourceDir.relativize(path).toString().replace(File.separatorChar, '/');
                    TarArchiveEntry entry = new TarArchiveEntry(path.toFile(), entryName);
                    try {
                        tos.putArchiveEntry(entry);
                        Files.copy(path, tos);
                        tos.closeArchiveEntry();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            tos.finish();
        }
    }
}